package com.tju.shortlink.project.config.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@RequiredArgsConstructor
@Configuration
@Slf4j
public class RabbitMqConfiguration {

    private final ConnectionFactory rabbitConnectionFactory;

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(rabbitConnectionFactory);
        //默认是用jdk序列化
        //数据转换为json存入消息队列，方便可视化界面查看消息数据
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        //CorrelationData, boolean b, String s
        rabbitTemplate.setConfirmCallback(
                (correlationData, b, s) -> {
                    log.info("ConfirmCallback     "+"相关数据："+  correlationData);
                    log.info("ConfirmCallback     "+"确认情况："+b);
                    log.info("ConfirmCallback     "+"原因："+s);
                });
        //returnedMessage
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.info("ReturnCallback：     "+"消息："+returnedMessage.getMessage());
            log.info("ReturnCallback：     "+"回应码："+returnedMessage.getReplyCode());
            log.info("ReturnCallback：     "+"回应消息："+returnedMessage.getReplyText());
            log.info("ReturnCallback：     "+"交换机："+returnedMessage.getExchange());
            log.info("ReturnCallback：     "+"路由键："+returnedMessage.getRoutingKey());
        });

        return rabbitTemplate;
    }

}
